package com.wanpinghui.wphlibrary.photovideo.view;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.wanpinghui.wphlibrary.R;
import com.wanpinghui.wphlibrary.photovideo.bean.UploadFileBean;
import com.wanpinghui.wphlibrary.photovideo.interfaces.OnActionListener;
import com.wanpinghui.wphlibrary.photovideo.interfaces.OnRecyclerItemClickListener;
import com.yunshl.yunshllibrary.recyclerview.YunGridLayoutManager;
import com.yunshl.yunshllibrary.utils.LogUtils;
import com.yunshl.yunshllibrary.utils.TextUtil;

import org.xutils.common.util.DensityUtil;

import java.util.ArrayList;
import java.util.Collections;

/***
 * 功能描述:
 * 作者:qiujialiu
 * 时间:2016/12/20
 * 版本:1.0
 ***/

public class ProductImageUploadView extends LinearLayout {
    private Context mContext;
    private View mView;
    private RecyclerView mRecyclerView;
    private ItemTouchHelper mHelper;
    private ArrayList<UploadFileBean> imagePaths;
    private MAdapter mAdapter;

    public int getMaxCount() {
        return maxCount;
    }

    private int maxCount = 9;
    private int spanCount = 3;
    private OnActionListener mListener;
    private boolean mHaveMainImage = false;

    public boolean isSubmit() {
        return IsSubmit;
    }

    public void setSubmit(boolean submit) {
        IsSubmit = submit;
    }

    private boolean IsSubmit = false;
    private boolean haveMoreItem = true;

    private String addContentString ;

    public ProductImageUploadView(Context context) {
        this(context, null);
    }

    public ProductImageUploadView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public ProductImageUploadView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = null;
        if (attrs != null) {
            typedArray = context.obtainStyledAttributes(attrs, R.styleable.ProductImageUploadView);
            maxCount = typedArray.getInt(R.styleable.ProductImageUploadView_max_count, 9);
            spanCount = typedArray.getInt(R.styleable.ProductImageUploadView_span_count, 3);
        }
        init(context);
        if (typedArray != null) {
            typedArray.recycle();
        }
    }

    public void setOnActionListener(OnActionListener listener) {
        this.mListener = listener;
        mAdapter.setOnActionListener(mListener);
    }

    public void setHaveMoreItem(boolean haveMoreItem) {
        this.haveMoreItem = haveMoreItem;
    }

    public boolean haveActionListener() {
        return mListener != null;
    }

    public void setHaveMainImage(boolean haveMainImage) {
        this.mHaveMainImage = haveMainImage;
        mAdapter.setHaveMain(haveMainImage);
    }

    public void notifyItemChange(int position) {
        mAdapter.notifyItemChanged(position);
    }

    public ArrayList<UploadFileBean> getImagePaths() {
        return imagePaths;
    }

    public void setMaxCount(int maxCount) {
        if (maxCount > 0) {
            this.maxCount = maxCount;
            mAdapter.setMaxCount(maxCount);
        }
    }

    public void setProcess(double process) {
        mAdapter.getUploadingView().setProgress(process);
    }

    //public void setStatus()

    public void setAllReady(int beginIndex) {
        if (imagePaths != null && imagePaths.size() > 0) {
            for (int i = 0; i < imagePaths.size(); i++) {
                if (beginIndex == i) {
                    imagePaths.get(i).setStatus(UploadFileBean.STATUS_BEGIN_UPLOAD);
                } else {
                    imagePaths.get(i).setStatus(UploadFileBean.STATUS_WAIT_UPLOAD);
                }
            }
        }
        mAdapter.setData(imagePaths);
    }

    public void beginUpload(int index) {
        if (imagePaths != null && imagePaths.size() > index) {
            imagePaths.get(index).setStatus(UploadFileBean.STATUS_BEGIN_UPLOAD);
            mAdapter.notifyItemChanged(index);
        }
    }

    public void setUploadResult(int index, boolean success) {
        if (imagePaths != null && imagePaths.size() > index) {
            imagePaths.get(index).setStatus(UploadFileBean.STATUS_COMMON);
            mAdapter.notifyItemChanged(index);
        }
    }

    public void setData(ArrayList<UploadFileBean> data) {
        this.imagePaths = data;
        mAdapter.setData(data);
    }

    private void init(Context context) {
        this.mContext = context;
        mView = LayoutInflater.from(context).inflate(R.layout.view_upload_group_view, this);
        mRecyclerView = (RecyclerView) mView.findViewById(R.id.rl_upload_groud);
        mAdapter = new MAdapter(context);
        mAdapter.setMaxCount(maxCount);
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setLayoutManager(new YunGridLayoutManager(context, spanCount));
        initTouchHelper();
        mHelper.attachToRecyclerView(mRecyclerView);
        mRecyclerView.addOnItemTouchListener(new OnRecyclerItemClickListener(mRecyclerView) {
            @Override
            public void onItemClick(RecyclerView.ViewHolder vh) {

            }

            @Override
            public void onItemLongClick(RecyclerView.ViewHolder vh) {
                if (imagePaths != null) {
                    if (imagePaths.size() == maxCount) {
                        mHelper.startDrag(vh);
                    } else {
                        if (vh.getLayoutPosition() != mAdapter.getItemCount() - 1) {
                            mHelper.startDrag(vh);
                        }
                    }
                }
            }
        });
    }

    private void initTouchHelper() {
        mHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                final int swipeFlags = 0;
                return makeMovementFlags(dragFlags, swipeFlags);
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                int fromPosition = viewHolder.getAdapterPosition();//得到拖动ViewHolder的position
                int toPosition = target.getAdapterPosition();//得到目标ViewHolder的position

                if (canMove(fromPosition, toPosition)) {
                    if (mListener != null) {
                        mListener.onItemPositionChange();
                    }
                    if (fromPosition < toPosition) {
                        for (int i = fromPosition; i < toPosition; i++) {
                            Collections.swap(imagePaths, i, i + 1);
                        }
                    } else {
                        for (int i = fromPosition; i > toPosition; i--) {
                            Collections.swap(imagePaths, i, i - 1);
                        }
                    }
                    mAdapter.notifyItemMoved(fromPosition, toPosition);
                }
                return true;
            }

            @Override
            public boolean isLongPressDragEnabled() {
                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {

            }

            @Override
            public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
                if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
                    ObjectAnimator animator = ObjectAnimator.ofFloat(viewHolder.itemView, "scaleX", 1f, 1.2f);
                    ObjectAnimator animator2 = ObjectAnimator.ofFloat(viewHolder.itemView, "scaleY", 1f, 1.2f);
                    AnimatorSet set = new AnimatorSet();
                    set.setDuration(200).play(animator).with(animator2);
                    set.start();
                }
                super.onSelectedChanged(viewHolder, actionState);
            }

            @Override
            public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                super.clearView(recyclerView, viewHolder);
                ObjectAnimator animator = ObjectAnimator.ofFloat(viewHolder.itemView, "scaleX", 1.2f, 1f);
                ObjectAnimator animator2 = ObjectAnimator.ofFloat(viewHolder.itemView, "scaleY", 1.2f, 1f);
                AnimatorSet set = new AnimatorSet();
                set.setDuration(200).play(animator).with(animator2);
                set.start();
            }
        });
    }

    private boolean canMove(int fromPosition, int toPosition) {
        if (imagePaths.size() < 9) {
            return fromPosition < mAdapter.getItemCount() - 1 && toPosition < mAdapter.getItemCount() - 1 && imagePaths.get(toPosition).getType() != 2;
        } else {
            return fromPosition < mAdapter.getItemCount() && toPosition < mAdapter.getItemCount() && imagePaths.get(toPosition).getType() != 2;
        }
    }

    public void addData(UploadFileBean bean) {
        if (imagePaths == null) {
            imagePaths = new ArrayList<>();
        }
        imagePaths.add(bean);
        mAdapter.notifyItemInserted(imagePaths.size() - 1);
    }



    public String getAddContentString() {
        return addContentString;
    }

    public void setAddContentString(String addContentString) {
        this.addContentString = addContentString;
    }

    private class MAdapter extends RecyclerView.Adapter {
        private static final int TYPE_ADD = 1;
        private static final int TYPE_IMAGE = 2;
        private ArrayList<UploadFileBean> imagePaths;
        private Context mContext;
        private YunUploadView uploadingView;
        private int maxCount;
        private OnActionListener mListener;
        private boolean haveMain;

         MAdapter(Context context) {
            this.mContext = context;
        }

        void setHaveMain(boolean haveMain) {
            this.haveMain = haveMain;
        }

         void setOnActionListener(OnActionListener listener) {
            this.mListener = listener;
        }

         void setMaxCount(int count) {
            this.maxCount = count;
        }

         YunUploadView getUploadingView() {
            return uploadingView;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == TYPE_ADD) {
                return new LastHolder(createView(parent, viewType));
            } else {
                return new GridHolder(createView(parent, viewType));
            }
        }

        public void setData(ArrayList<UploadFileBean> data) {
            this.imagePaths = data;
//            if (imagePaths!=null && imagePaths.size()<maxCount){
//                if (imagePaths.get(imagePaths.size()-1).getType()!=3) {
//                    imagePaths.add(new UploadFileBean(3));
//                }
//            }
            notifyDataSetChanged();
        }

        private View createView(ViewGroup parent, int viewType) {
            //int width = getWidth(parent);
            if (viewType == TYPE_ADD) {
                //itemView.setLayoutParams(new ViewGroup.LayoutParams(width / 3, width / 3));
                return LayoutInflater.from(mContext).inflate(R.layout.item_recycler_upload_group_last, null);
            } else {
                //LogUtils.w("ProductImageUploadView","width = "+(width / 3)+"===height = "+(width / 3));
                //itemView.setLayoutParams(new ViewGroup.LayoutParams(width / 3, width / 3));
                return LayoutInflater.from(mContext).inflate(R.layout.item_recycler_upload_group, null);
            }
        }

        @Override
        public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
            if (TYPE_ADD == getItemViewType(position)) {
                ((LastHolder) holder).mTextView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mListener != null) {
                            mListener.onAddMoreClick();
                        }
                    }
                });
                if (TextUtil.isNotEmpty(addContentString)){
                    ((LastHolder) holder).mTextView.setBackground(ContextCompat.getDrawable(mContext,R.drawable.shape_bg_blue_stroke));
                    ((LastHolder) holder).mTextView.setText(addContentString);
                }
                ProductImageUploadView.this.post(new Runnable() {
                    @Override
                    public void run() {
                        int width = (int)(ProductImageUploadView.this.getMeasuredWidth()/((float)spanCount));

                        width = width - DensityUtil.dip2px(12);

                        LogUtils.w("ProductImageUploadView", "item width second: "+width);
                        if (width > 0) {
                            ((LastHolder) holder).mTextView.setLayoutParams(new LayoutParams(width,width));
                        }
                    }
                });
            } else {

                final UploadFileBean bean = imagePaths.get(position);
                final GridHolder thisHolder = (GridHolder) holder;
                if (position == 0) {
                    thisHolder.mUploadView.setHaveMainImage(true);
                    thisHolder.mUploadView.setMainImage(true);
                } else {
                    thisHolder.mUploadView.setMainImage(false);
                }
                if (bean.getType() == 2) {
                    thisHolder.mUploadView.setIsVideo(true);
                    //视频
                        thisHolder.mUploadView.setContent(bean.getForderPath(),null);
                } else {
                    thisHolder.mUploadView.setIsVideo(false);
                    thisHolder.mUploadView.setContent(imagePaths.get(position).getPath(), null);
                }
                if (bean.getStatus() == UploadFileBean.STATUS_UPLOADING || bean.getStatus() == UploadFileBean.STATUS_BEGIN_UPLOAD) {
                    uploadingView = thisHolder.mUploadView;
                }
                if (bean.getStatus() == UploadFileBean.STATUS_UPLOADING) {
                    thisHolder.mUploadView.setProgress(imagePaths.get(position).getProcess());
                } else if (bean.getStatus() == UploadFileBean.STATUS_BEGIN_UPLOAD) {
                    thisHolder.mUploadView.beginUpload();
                } else if (bean.getStatus() == UploadFileBean.STATUS_WAIT_UPLOAD) {
                    thisHolder.mUploadView.readyToUpload();
                } else {
                    thisHolder.mUploadView.resetView();
                }
                thisHolder.mUploadView.getDeleteView().setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mListener != null) {
                            mListener.onItemDelete(position);
                        }
                    }
                });
                thisHolder.mUploadView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mListener != null) {
                            mListener.onItemClick(position);
                        }
                    }
                });
                if (haveMain) {
                    thisHolder.mUploadView.setMainImage(true);
                } else {
                    thisHolder.mUploadView.setMainImage(false);
                }
                int width = (int)(ProductImageUploadView.this.getMeasuredWidth()/((float)spanCount));
                LogUtils.w("ProductImageUploadView", "item width : "+width);
                if (width == 0) {
                    ProductImageUploadView.this.post(new Runnable() {
                        @Override
                        public void run() {
                            int width = (int)(ProductImageUploadView.this.getMeasuredWidth()/((float)spanCount));
                            LogUtils.w("ProductImageUploadView", "item width second: "+width);
                            if (width > 0) {
                                thisHolder.mLayoutItim.setLayoutParams(new LayoutParams(width,width));
                            }
                        }
                    });

                }else {
                    thisHolder.mLayoutItim.setLayoutParams(new LayoutParams(width,width));
                }
                if (IsSubmit) {
                    thisHolder.mUploadView.setDiss();
                }
            }
        }


        @Override
        public int getItemCount() {
                if (imagePaths == null || imagePaths.size() == 0) {
                    return 1;
                } else {
                    if (imagePaths.size() == maxCount || !haveMoreItem) {
                        return imagePaths.size();
                    } else {
                        return imagePaths.size() + 1;
                    }
                }
            // return imagePaths==null?0:imagePaths.size();
        }

        @Override
        public int getItemViewType(int position) {

                if (imagePaths != null && imagePaths.size()>0) {
                    if ((position == imagePaths.size() && haveMoreItem)) {
                        return TYPE_ADD;
                    } else {
                        return TYPE_IMAGE;
                    }
                }else {
                    if (position == 0 && haveMoreItem){
                        return TYPE_ADD;
                    } else {
                        return TYPE_IMAGE;
                    }
                }

        }

        class GridHolder extends RecyclerView.ViewHolder {
            YunUploadView mUploadView;
            LinearLayout mLayoutItim;

             GridHolder(View itemView) {
                super(itemView);
                mUploadView = (YunUploadView) itemView.findViewById(R.id.yuv_upload);
                mLayoutItim = (LinearLayout) itemView.findViewById(R.id.ll_item);
            }
        }

        class LastHolder extends RecyclerView.ViewHolder {
            TextView mTextView;

            LastHolder(View itemView) {
                super(itemView);
                mTextView = (TextView) itemView.findViewById(R.id.tv_add_detail);
            }
        }

    }
}
